<template>
	<view class="container" style="padding-bottom: 100px" v-if="isLoaded">
		<view class="content" style="padding: 30rpx 30rpx 120rpx; background-color: #fff">
			<li-form ref="form">
				<li-form-item label="活动名称" required>
					<li-input placeholder="请输入活动名称" v-model="form.name" rule="trim" prop="name" v-on:blur="onBlurEvent($event)" />
				</li-form-item>
				<li-form-item label="活动编码" required>
					<li-input placeholder="请输入活动编码" rule="trim" v-model="form.code" prop="code" />
				</li-form-item>
				<li-form-item label="活动时间" required>
					<uni-datetime-picker
						start-placeholder="请选择开始时间"
						end-placeholder="请选择开始时间"
						v-model="form.validityRange"
						type="datetimerange"
						rangeSeparator="至"
					/>
				</li-form-item>
				<!--    <li-form-item label="不可用日期">
          <li-checkbox v-model="form.noDate" />
        </li-form-item> -->
				<li-form-item label="活动说明">
					<li-textarea placeholder="请输入活动说明" v-model="form.desc" />
				</li-form-item>

				<!-- <li-form-item label="适用门店">
          <view>小桂林（东葛店）</view>
        </li-form-item> -->
				<li-form-item label="适用会员">
					<li-picker
						v-model="form.isApplyMember"
						:rangeList="[
							{
								id: true,
								text: `全部`
							},
							{
								id: false,
								text: `指定会员`
							}
						]"
						rangeKey="text"
						rangeValue="id"
					/>
				</li-form-item>

				<li-form-item label="会员选择" v-if="!form.isApplyMember">
					<li-checkbox v-model="form.userGrades" :rangeList="UserGradeList" :rangeKey="'title'" />
				</li-form-item>

				<view style="display: flex; align-items: center; justify-content: flex-start">
					<text style="width: 80px; font-weight: bold">领取优惠券:</text>
					<view
						:style="{
							backgroundColor: '#f3c45d',
							color: '#fff',
							borderRadius: '8px',
							padding: '5px 8px'
						}"
						v-on:click="
							() => {
								batchGetData([
									{
										fn: popPageFn,
										name: `popPageList`
									}
								]);
								show = true;
							}
						"
					>
						选择优惠券
					</view>
				</view>
				<view class="spec-container">
					<view class="spec-body">
						<block v-if="form.rule.length > 0">
							<view>
								<view class="items" style="border-bottom: 1px solid #cacaca; padding: 8px 0">
									<view class="is-default">名称</view>
									<view class="spec-name task-price">数量</view>
									<view class="btns task-btn">操作</view>
								</view>
							</view>
							<view v-for="(item, index) in form.rule" :key="item.id" class="items">
								<view class="is-default">
									<text>
										{{ item.name }}
									</text>
								</view>
								<view class="spec-name task-price">
									<li-input v-model="item.count" rule="int" style="width: 45px" />
								</view>

								<view class="btns task-btn">
									<text
										class="btn btn-del"
										@click="
											() => {
												form.rule.splice(index, 1);
											}
										"
										style="margin-left: 8px"
									>
										删除
									</text>
								</view>
							</view>
						</block>
						<block v-else>暂无优惠券~~</block>
					</view>
				</view>
				<view
					:style="{
						margin: `5px 0`
					}"
				>
					<text style="font-weight: bold; width: 80px; display: inline-block">用户限次:</text>
					以下至少选择一项为限制
				</view>
				<view style="display: flex; align-items: center">
					<block>每人每天可领取次数：</block>
					<li-picker
						style="flex: 1; margin-right: 3px"
						v-model="form.isUserDayStock"
						:rangeList="[
							{
								id: false,
								text: `不限制`
							},
							{
								id: true,
								text: `限制`
							}
						]"
					></li-picker>
					<block v-if="form.isUserDayStock">
						次数：
						<li-input v-model="form.userDayStock" style="flex: 1" />
					</block>
				</view>
				<view style="display: flex; align-items: center; margin-top: 5px">
					<block>每人可领取次数：</block>
					<li-picker
						style="flex: 1; margin-right: 3px; margin-left: 2em"
						v-model="form.isUserTotal"
						:rangeList="[
							{
								id: false,
								text: `不限制`
							},
							{
								id: true,
								text: `限制`
							}
						]"
					></li-picker>
					<block v-if="form.isUserTotal">
						次数：
						<li-input v-model="form.userTotal" style="flex: 1" />
					</block>
				</view>

				<li-form-item label="活动限次"></li-form-item>
				<view>
					<view>
						<view style="display: flex; align-items: center">
							活动每天可发放次数：
							<li-picker
								style="flex: 1; margin-right: 3px"
								v-model="form.isDayStock"
								:rangeList="[
									{
										id: false,
										text: `不限制`
									},
									{
										id: true,
										text: `限制`
									}
								]"
							></li-picker>
							<block v-if="form.isDayStock">
								次数：
								<li-input v-model="form.dayStock" style="flex: 1" />
							</block>
						</view>
					</view>
					<view style="display: flex; align-items: center; margin-top: 5px">
						活动总共可发放次数：
						<li-picker
							v-model="form.isTotal"
							style="flex: 1; margin-right: 3px"
							:rangeList="[
								{
									id: false,
									text: `不限制`
								},
								{
									id: true,
									text: `限制`
								}
							]"
						/>
						<block v-if="form.isTotal">
							次数：
							<li-input v-model="form.total" style="flex: 1" />
						</block>
					</view>
				</view>
			</li-form>
		</view>
		<!-- popup -->
		<li-popup
			:show="show"
			v-on:open="
				() => {
					show = true;
				}
			"
			v-on:close="
				() => {
					show = !true;
				}
			"
		>
			<view
				:style="{
					paddingTop: `50px`,
					paddingLeft: `8px`,
					paddingRight: `8px`,
					'overflow-y': `scroll`,
					height: `100%`
				}"
			>
				<view
					v-for="(item, index) in popPageList"
					:key="item.id"
					:style="{
						marginBottom: `10px`
					}"
					style="background-color: #fff; border-radius: 10px; padding: 12px 15px; display: flex; justify-content: space-between; align-items: center"
				>
					<view style="flex: 1; font-weight: bold">
						{{ item.name }}
					</view>
					<view style="flex: 1">
						{{ couponTypeEnum.find((it) => it.id == item.typeId).text }}
					</view>
					<view style="flex: 1">
						{{ item.parValue ? item.parValue + '元' : `-` }}
					</view>
					<view
						:style="{
							'background-color': form.rule.some((itm) => itm.id == item.id) ? '#f56c6c' : '#f3c45d',
							borderRadius: `8px`,
							padding: `3px 5px`,
							color: `#fff`
						}"
						v-on:click="
							() => {
								if (form.rule.some((itm) => itm.id == item.id)) {
									form.rule.splice(
										form.rule.findIndex((itm) => itm.id == item.id),
										1
									);
								} else {
									form.rule.push({
										id: item.id,
										name: item.name,
										count: 1,
										start: item.start,
										end: item.end
									});
								}
							}
						"
					>
						{{ form.rule.some((itm) => itm.id == item.id) ? '取消' : '选择' }}
					</view>
				</view>
			</view>
		</li-popup>

		<li-bottom-btns :zIndex="10" :mode="mode" v-on:btnDelClick="btnDelClick" v-on:btnEditOrSaveSubmitClick="btnEditOrSaveSubmitClick" />
	</view>
</template>
<script>
import liFormMixin from '../../../mixins/liFormMixin';

import dateUtils from '../../../utils/date.js';
import { transferTypeEnum } from '../../../common/dataTransfer.js';
import { checkerType, modeEnum, booleanEnum, weekEnumable, couponTypeEnum } from '../../../constants/normalConstants.js';
import { corpId, storeId } from '../../../constants/apiConstants.js';

import liValidateData, { validateTypeEnum } from '../../../utils/liValidator.js';
import { utoast } from '../../../utils/uniUtils.js';
import { GetFoodCouponList, GetUserGradeList } from '../../../common/api.js';
import { AddSalesPromotion, DelSalesPromotionById, EditSalesPromotion, GetSalesPromotionById } from '../../../common/modules/business.js';
export default {
	mixins: [liFormMixin],
	async onLoad(options) {
		this.loadEvent(options, this);
	},

	async mounted() {
		this.mountedEvent(this, {
			name: '',
			code: '',
			cycleType: 0,
			isDayStock: true,
			dayStock: 0,
			isTotal: true,
			total: 0,
			isUserDayStock: true,
			userDayStock: 0,
			isUserTotal: true,
			userTotal: 0,
			qRCode: '',
			type: 1,
			rule: [],
			status: 1,
			desc: '',
			stock: 3,
			validityRange: [dateUtils.getTomorrow(), dateUtils.getTomorrow()],
			userGradeList: [],
			userGrades: [],
			isApplyMember: true
		});
	},

	data() {
		return {
			modeEnum,
			weekEnumable,
			booleanEnum,
			couponTypeEnum,
			subject: '活动',
			rootRoute: 'workbench',
			routeName: 'couponScan',
			mode: 'add',
			isLoaded: false,
			id: null,
			getFn: GetSalesPromotionById,
			addFn: AddSalesPromotion,
			delFn: DelSalesPromotionById,
			editFn: EditSalesPromotion,
			popLeftFn: null,
			popLeftList: [],
			popPageFn: GetFoodCouponList,
			popPageList: [],
			otherDataFns: [
				{
					fn: GetUserGradeList,
					name: 'UserGradeList'
				}
			],
			/* form */
			form: null,
			/* popup */
			show: false,
			// transfer
			transferRules: [
				/*   {
          name: "programmeCode",
          type: transferTypeEnum.trim,
        },
        {
          name: "programmeName",
          type: transferTypeEnum.trim,
        }, */
			],
			//check rule
			rules: {
				name: {
					type: validateTypeEnum.string,
					required: true,
					message: '请填写活动名称'
				},
				code: {
					type: validateTypeEnum.string,
					required: true,
					message: '请填写编码'
				},
				validityRange: {
					type: validateTypeEnum.array,
					required: true,
					presence: true,
					message: '请选择活动日期',
					length: { exactly: 2 }
				},
				rule: {
					asyncValidator: (_rule, value, _callback) =>
						new Promise((resolve, reject) => {
							{
								if (value.length == 0) {
									reject('优惠券不能为空！');
								}
								if (value.some((item) => item.count < 1)) {
									reject('优惠券数量不能为空！');
								}
								resolve(true);
							}
						})
				}
			},
			lock: false,

			/* extra data */
			showAddFood: false,
			foodCategoryId: 0,
			foodList: [],
			foodCategoryList: [],
			type: 1,
			popPageList: [],
			StoreList: [],
			UserGradeList: []
			/* extra rules */

			/* extra transfer */
		};
	},

	methods: {
		async onBlurEvent(e) {
			this.formBlur(e, this);
		},

		async getOtherData() {
			await this.batchGetData(this.otherDataFns);
			let newObj = {};
			Object.assign(newObj, this.form, {
				isApplyMember: true
			});
			this.form = newObj;
			/*       Object.entries(this.form).forEach(
        (item) => (newObj[item[0]] = newObj[item[1]])
      );
      this.form = newObj; */
		},

		async btnEditOrSaveSubmitClick() {
			if (!(this.form.isUserDayStock || this.form.isUserTotal)) {
				await utoast('至少有一项限制~', 'error');
				return;
			}
			let arr = [];
			this.form.userGrades = this.form.userGrades == null ? [] : this.form.userGrades;
			this.UserGradeList.forEach((element) => {
				const res = this.form.userGrades.some((item) => item == element.id);
				if (res) {
					arr.push(element);
				}
			});
			this.form.userGradeList = arr;

			await this.formInsertOrEdit(this);
		}

		/* extra methods */

		// method put on the top
	}
};
</script>
<style lang="scss" scoped>
@import '~@/static/styles/commonStyle.scss';

.spec-container {
	background-color: #fff;
	border-radius: 10px;
	margin: 10px 0;
	padding: 8px 4px;

	.spec-header {
		padding: 10px;
		border-bottom: 1px solid #ededed;
		display: flex;
		justify-content: space-between;
	}

	.spec-body {
		padding: 15px 10px;

		.items {
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-size: 12px;
			border-bottom: 1px solid #cacaca;
			padding: 8px 0;
			&:last-child {
				border-bottom: none;
			}

			.is-default {
				width: 80px;
				display: flex;
				justify-content: center;
				color: #000;
				background-color: #fff;
				.is-default-active {
					color: #fff;
					background-color: #fdc31d;
				}
			}

			.spec-name {
				flex: 1;
				display: flex;
				justify-content: center;
				&.task-price {
					width: 80px;
				}
			}

			.price {
				width: 80px;
				display: flex;
				justify-content: center;
				&.task-option {
					width: 70px;
				}
			}

			.btns {
				width: 90px;
				display: flex;
				justify-content: center;
				&.task-btn {
					width: 70px;
					font-size: 12px;
				}
			}

			.btn {
				border: 1px solid #ededed;
				padding: 12rpx 12rpx;
				border-radius: 5rpx;
				&.btn-del {
					background-color: #f56c6c;
					color: #fff;
				}
			}
		}
	}
}
</style>